import sys
from datetime import datetime

from PyQt5.QtWidgets import QMainWindow, QApplication, QTabBar, QWidget, QVBoxLayout
from service.console_service import ConsoleService
from UI.ConsoleForm import UI_ConsoleForm
from service.console_service import ConsoleService

class ConsoleController(UI_ConsoleForm):
    def __init__(self):
        super().__init__()
        self.set_elements()
        self.connect()

    def connect(self):
        n = self.depth
        for i in range(n):
            if self.qty - (i + 1) * 4 < 0:#机器人数据量不是4的倍数或者小于4，对列循环次数进行控制
                m = 4 + (self.qty - (i + 1) * 4)
            else:
                m = 4
            for j in range(m):
                button=self.elements[i][j][3]
                button.clicked.connect(lambda state,row=i,col=j: self.stop_user(row,col))

    def stop_user(self, row, col):
        button = self.elements[row][col][3]
        label_robot_no = self.elements[row][col][0]
        robot_no =label_robot_no.text()
        console_service = ConsoleService(user=robot_no,states=0)
        console_service.stop_user()
        button.setText(f' {row}{col}{robot_no}已经停止运行')
        button.setEnabled(False)
        print("点击按钮：{}{}".format(row, col))

    def set_elements(self):
        users =ConsoleService.get_work_users()
        n = self.depth
        for i in range(n):
            if self.qty - (i + 1) * 4 < 0:#机器人数据量不是4的倍数或者小于4，对列循环次数进行控制
                m = 4 + (self.qty - (i + 1) * 4)
            else:
                m = 4
            y = 0
            for j in range(m):
                label_robot_no = self.elements[i][j][0]
                label_robot_no.setText(users[y].user)
                label_robot_type = self.elements[i][j][1]
                label_robot_type.setText(users[y].describe)
                label_working_time = self.elements[i][j][2]
                label_working_time.setText(str(datetime.now().replace(microsecond=0)-datetime.fromtimestamp(users[y].start_time)))
                y=y+1

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = ConsoleController()
    window.show()
    sys.exit(app.exec_())